﻿using System;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace MQAMS
{
    public class XlsHelper
    {
        private static readonly XlsHelper Helper = new XlsHelper();

        private ISheet _sheet;
        private IWorkbook _workbook;

        private int _index;

        private XlsHelper()
        {
            Initial();
        }

        public static XlsHelper Instance
        {
            get { return Helper; }
        }

        private void SetHeader()
        {
            IRow row = _sheet.CreateRow(0);
            _index++;
            row.CreateCell(0).SetCellValue("工号");
            row.CreateCell(1).SetCellValue("姓名");
            row.CreateCell(2).SetCellValue("部门");
            row.CreateCell(3).SetCellValue("刷卡日期");
            row.CreateCell(4).SetCellValue("星期");
            row.CreateCell(5).SetCellValue("次数");
            row.CreateCell(6).SetCellValue("1");
            row.CreateCell(7).SetCellValue("2");
            row.CreateCell(8).SetCellValue("3");
        }

        private void Initial()
        {
            _workbook = new HSSFWorkbook();
            _sheet = _workbook.CreateSheet("Sheet1");
            _index = 0;
            SetHeader();
        }

        public void AddData(Attendance attendance)
        {
            IRow row = _sheet.CreateRow(_index);
            _index++;

            row.CreateCell(0).SetCellValue(attendance.Id);
            row.CreateCell(1).SetCellValue(attendance.Name);
            row.CreateCell(2).SetCellValue(attendance.Depart);
            row.CreateCell(3).SetCellValue(attendance.Date.ToShortDateString());
            row.CreateCell(4).SetCellValue(attendance.Weekday);
            row.CreateCell(5).SetCellValue(attendance.Times);
            row.CreateCell(6).SetCellValue(attendance.StartTime);
            row.CreateCell(7).SetCellValue(attendance.SecTime);
            row.CreateCell(8).SetCellValue(attendance.ThiTime);
        }

        public void ExportXls(string path)
        {
            using (FileStream stm = File.OpenWrite(path + DateTime.Now.ToFileTime() + ".xls"))
            {
                _workbook.Write(stm);
            }
            Initial();
        }
    }
}